<script lang="ts" setup>
	import { onLaunch, onShow, onHide } from '@dcloudio/uni-app'
	import { onMounted, onBeforeUnmount, ref } from 'vue'
	onLaunch(()=>{
		console.log('App Launch')
	})
	onShow(()=>{
		console.log('App Launch')
	})
	onHide(()=>{
		console.log('App Launch')
	})
	
	const autoRedirect = ref(true);
	const shouldRedirect = ref(true);
	const baseUrl = 'https://www.cqjsyh.com';
	const webUrl = `${baseUrl}/web`;
	const mobileUrl = `${baseUrl}/H5`;
	const isMobile = ref(false);
	const breakpoint = 768; // 桌面/移动断点
	
	// 设备检测函数
	const detectDevice = () => {
	  const userAgent = navigator.userAgent.toLowerCase();
	  const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
	  const isMobileByAgent = /mobile|android|iphone|ipad|ipod/i.test(userAgent);
	  const isMobileByWidth = window.innerWidth < breakpoint;
	  
	  return isMobileByAgent || (isTouchDevice && isMobileByWidth);
	};
	
	// 获取当前路径
	// 判断是否需要跳转
	const checkIfNeedRedirect = () => {
	  const currentPath = window.location.href
	  
	  const isOnWebPath = currentPath.includes('web');
	  const isOnMobilePath = currentPath.includes('H5');
	  // 如果已经在正确的路径上，则不需要跳转
	  if ((isMobile.value && isOnMobilePath) || (!isMobile.value && isOnWebPath)) {
	    return false;
	  }
	  
	  // 其他情况需要跳转
	  return true;
	};
	
	// 执行跳转
	const redirect = () => {
	  try {
	    if (!shouldRedirect.value) {
	      console.log('当前页面已匹配设备类型，跳过重定向');
	      return;
	    }
	    
	    const targetUrl = isMobile.value ? mobileUrl : webUrl;
	    // window.location.href = targetUrl;
	  } catch (error) {
	    console.error('自动跳转失败:', error);
	    autoRedirect.value = false;
	  }
	};
	
	// 窗口大小变化监听
	const handleResize = () => {
	  const prevIsMobile = isMobile.value;
	  isMobile.value = detectDevice();
	  
	  // 只有在设备类型变化且需要跳转时才执行
	  if (prevIsMobile !== isMobile.value) {
	    shouldRedirect.value = checkIfNeedRedirect();
	    if (shouldRedirect.value) {
	      redirect();
	    }
	  }
	};
	
	onMounted(() => {
	  isMobile.value = detectDevice();
	  shouldRedirect.value = checkIfNeedRedirect();
	  
	  if (shouldRedirect.value) {
	    redirect();
	  }
	  
	  // 添加窗口大小变化监听
	  window.addEventListener('resize', handleResize);
	});
	
	onBeforeUnmount(() => {
	  // 移除监听，防止内存泄漏
	  window.removeEventListener('resize', handleResize);
	});
</script>

<style>
	/*每个页面公共css */
	.container{
		max-width: 750rpx;
		margin: 0 auto;
	}
</style>
